using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace Rioshu.Web.ViewStateHandlers
{
    internal sealed class GzipCompressor : IStringCompressor
    {
        public string Compress(string input)
        {
            var memStream = new MemoryStream();
            using (var gzipStream = new GZipStream(memStream, CompressionMode.Compress)) {
                var buffer = Encoding.UTF8.GetBytes(input);
                gzipStream.Write(buffer, 0, buffer.Length);
            }

            var outputBytes = memStream.ToArray();
            memStream.Close();

            return Convert.ToBase64String(outputBytes);
        }

        public string Decompress(string input)
        {
            var outStream = new MemoryStream();
            var inStream = new MemoryStream(Convert.FromBase64String(input));
            using (var gzipStream = new GZipStream(inStream, CompressionMode.Decompress)) {
                int read = 0;
                var buffer = new byte[4096];
                while ((read = gzipStream.Read(buffer, 0, buffer.Length)) != 0) {
                    outStream.Write(buffer, 0, read);
                }
            }
            var outBytes = outStream.ToArray();

            inStream.Close();
            outStream.Close();

            return Encoding.UTF8.GetString(outBytes);
        }
    }
}